<template>
  <div class="upload">
    <div
      class="upload-content"
      @click="onUpload"
      @drop="drop"
      @dragenter="dragEnter"
      @dragleave="dragLeave"
      @dragover="dragOver"
      draggable="true"
    >
      <input
        ref="inputElRef"
        @change="onChange"
        type="file"
        name="upload"
        id="upload"
        v-show="false"
      />
      <div class="upload-drag">
        <el-icon size="80" color="#a8abb2"><UploadFilled /></el-icon>
        <div>将文件拖拽上传或 <em>点击上传</em></div>
      </div>
    </div>
    <div class="upload-tip"></div>
    <div class="upload-preview">
      <img v-for="(file, src) in previewFileList" :src="file" alt="" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { UploadFilled } from "@element-plus/icons-vue";

const previewFileList = ref();
const inputElRef = ref<Element | undefined>();

/**
 * 文件选择改变
 * @param e 事件参数
 */
const onChange = (e: any) => {
  console.log(e, "onChange");
  const file = e.target.files?.[0];
  // 限制文件大小
  if (file.size > 10 * 1024 * 1024) {
    window.alert("文件大小不能超过10M");
    return;
  }
  // 限制文件类型
  if (!["image/png", "image/jpeg", "image/jpg"].includes(file.type)) {
    window.alert("文件类型只能是png/jpg/jpeg");
    return;
  }
  readFilePreview(file);
};

/**
 * 读取文件预览
 * @param file 文件
 */
const readFilePreview = (file: any) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    console.log(e.target?.result, "onload");

    previewFileList.value = e.target?.result;
  };
  reader.readAsDataURL(file);
  //   reader.readAsText(file);
};

/**
 * 点击文件上传按钮
 */
const onUpload = () => {
  inputElRef.value.click();
};

const dragEnter = (e: Event) => {
  // console.log(e, "dragEnter");
};

const dragLeave = (e: Event) => {
  // console.log(e, "dragLeave");
};

const dragOver = (e: Event) => {
  e.preventDefault();
  // console.log(e, "dragOver");
};

const drop = (e: Event) => {
  e.preventDefault();
  console.log(e, "drag");
};
</script>

<style scoped land="scss">
.upload-content {
  width: 40vw;
  height: 30vh;
  border: 1px dashed gray;
  cursor: pointer;
  border-radius: 4px;

  &:hover {
    border-color: #409eff;
  }
  .upload-drag {
    em {
      color: #409eff;
      font-style: normal;
    }
  }
}
</style>
